# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1029070': {  # 苹果派 喵喵支付，支付宝费率2.5%，单笔（100---5000） loki
        'API_KEY': 'JfjduMIDR2THSln8AOJ9cgoluePkygWB',
        'gateway': 'http://api.miaomiao6.com/index/unifiedorder?format=json',
        'query_gateway': 'http://api.miaomiao6.com/index/getorder',
    },
    '1069573': {  # 喵喵支付，支付宝费率2.5%，单笔（10---1万），下发的单笔最低1000最高3w5
        'API_KEY': 'umSgDOaYxg5ckWk7jrtZ5IKOqu35VWpQ',
        'gateway': 'http://api.miaomiao6.com/index/unifiedorder?format=json',
        'query_gateway': 'http://api.miaomiao6.com/index/getorder',
    },
    '1056660': {  # 喵喵支付，支付宝费率2.5%，单笔（200---5000）
        'API_KEY': 'Quo6keJvTivWUb9w4mDfcg5Gg8GTZ3IR',
        'gateway': 'http://api.miaomiao6.com/index/unifiedorder?format=json',
        'query_gateway': 'http://api.miaomiao6.com/index/getorder',
    },
    '1019590': {  # 喵喵支付，支付宝费率2.5%，单笔（200---5000） loki
        'API_KEY': 'uQazO72oaCUdDtURr44JaSRZ9WSlp2fB',
        'gateway': 'http://api.miaomiao6.com/index/unifiedorder?format=json',
        'query_gateway': 'http://api.miaomiao6.com/index/getorder',
    },
}


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay_tra'
    elif service == 'qr_alipay':
        return 'alipaySolidCode'
    elif service == 'alipay_bank':
        return 'bank'
    else:
        return 'alipay_tra'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# 签名
def generate_sign(parameter, key):
    m = hashlib.md5()
    for k, v in parameter.items():
        if v == '':
            parameter.pop(k)
    par = sorted(parameter.items())
    param = ''
    for k, v in par:
        param += k + '=' + str(v) + '&'
    par_key = param + 'key=' + key
    m.update(par_key.encode('utf-8'))
    sign = m.hexdigest().upper()
    return sign


# 签名对照
def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("miaomiaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    # 商户ID唯一标识
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        # 商务号
        ('appid', str(app_id)),
        # 请求类型
        ('pay_type', _get_pay_type(service)),
        # 支付金额(元)
        ('amount', ('%.2f' % pay_amount)),
        # 回调地址
        ('callback_url', '{}/pay/api/{}/miaomiaopay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        # 同步通知地址，支付成功直接跳转的地址
        ('success_url', '{}/pay/api/{}/miaomiaopay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        # 失败跳转地址
        ('error_url', 'http://error.com'),
        ('out_uid', '1234'),
        # 商户订单号
        ('out_trade_no', str(pay.id)),
        # 接口版本
        ('version', 'v2.0'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("miaomiaopay create  data: %s", parameter_dict)
    response = requests.post(_get_gateway(app_id), json=parameter_dict, timeout=3)
    res_json = json.loads(response.text)
    _LOGGER.info("miaomiaopay return  data: %s", res_json)
    if res_json['code'] == 200:
        url = res_json['data']['qrcode']
        # html = str(url).replace('\\', '').strip()
        # cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("miaomiaopay create rsp url: %s,message: %s", url, res_json['msg'])
        return {'charge_info': url}
    else:
        return {'charge_info': res_json['msg']}


# OK
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("miaomiaopay notify data1: %s", data)
    _LOGGER.info("miaomiaopay notify body: %s", request.body)
    api_key = _get_api_key(app_id)
    # 校验sign
    verify_notify_sign(data, api_key)
    # 商户订单号
    pay_id = data['out_trade_no']
    # ip检查
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("miaomiaopay fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('miaomiaopay event does not contain pay ID')
    # 获取支付订单信息
    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['callbacks'])
    trade_no = data['out_trade_no']
    total_fee = float(data['amount_true'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    # 交易条件的判断，信息对比等
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'CODE_SUCCESS':
        _LOGGER.info('miaomiaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_id)


# 查询订单接口
def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('appid', app_id),
        ('out_trade_no', pay_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("miaomiaopay query data: %s, order_id: %s", json.dumps(parameter_dict),
                 parameter_dict['out_trade_no'])
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, timeout=5)
    _LOGGER.info("miaomiaopay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text).get('data')
        trade_status = str(data[0]['status'])
        trade_no = str(data[0]['out_trade_no'])
        total_fee = float(data[0]['amount'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == '4':
            _LOGGER.info('miaomiaopay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('miaomiaopay data error, status_code: %s', response.status_code)
